package com.siemens.industrial.web.mvc.dao.admin;

import com.siemens.industrial.model.admin.UserEventRelation;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Types;
import java.util.List;
import java.util.Map;

/**
 * Created by qupen on 2016/9/18.
 */
@Service
public class UserEventRelationDao {
    @Resource
    JdbcTemplate jdbcTemplate;

    public static final String addRelation = "INSERT INTO `siemens`.`user_event_relation` (`user_id`,`event_id`,`email`,`enabled`) VALUES(?,?,?,?)";
    public static final String changeRelation = "UPDATE `siemens`.`user_event_relation` SET `enabled`=? WHERE `user_id`=? AND `event_id`=?";
    public static final String deleteRelation = "DELETE FROM `siemens`.`user_event_relation` WHERE `user_id`=? AND `event_id`=?";
    public static final String deleteAllByUserId="DELETE FROM `siemens`.`user_event_relation` WHERE `user_id`=?;";
    public static final String findAllByUserId="SELECT event_id FROM `siemens`.`user_event_relation` WHERE `user_id`=?;";

    /**
     * 新增关联
     *
     * @param userEventRelation
     */
    public void save(UserEventRelation userEventRelation) {
        jdbcTemplate.update(addRelation, pss -> {
                    pss.setString(1, userEventRelation.getUserId());
                    pss.setString(2, userEventRelation.getEventId());
                    pss.setString(3, userEventRelation.getEmail());
                    pss.setInt(4, userEventRelation.getEnabled());
                }
        );
    }

    @Transactional
    public int update(int enabled, String userId, String eventId) {
        return jdbcTemplate.update(changeRelation, enabled, userId, eventId);
    }

    @Transactional
    public int deleteRelation(String userId, String eventId) {
        return jdbcTemplate.update(deleteRelation, userId, eventId);
    }

    @Transactional
    public int deleteAllRelation(String userId) {
        return jdbcTemplate.update(deleteAllByUserId, userId);
    }

    public List<Map<String,Object>> getAllByUserId(String userId){
        return jdbcTemplate.queryForList(findAllByUserId,userId);
    }
}
